package com.ljl.ningwei.domain;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ljl.ningwei.common.constant.PageConstant;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Data
public class Wp {

    private String wp;

    private Integer pageNum;

    private Integer pageSize;


    public Wp(String wp) throws JsonProcessingException {
        this.wp = wp;
        this.pageNum  = PageConstant.pageNum;
        this.pageSize = PageConstant.pageSize;
        if (StringUtils.isNotBlank(wp)) {
            String decode = URLDecoder.decode(wp, StandardCharsets.UTF_8);
            pageNum = parsePage(decode, "pageNum", PageConstant.pageNum);
            pageSize = parsePage(decode, "pageSize", PageConstant.pageSize);
        }
    }

    private int parsePage(String encode, String word, int defaultValue) throws JsonProcessingException {
        ObjectMapper jsonMapper = new ObjectMapper();
        JsonNode rootNode = jsonMapper.readTree(encode);
        if (!rootNode.has(word) || rootNode.get(word).isNull()) {
            return defaultValue;
        }
        int value = rootNode.get(word).asInt();
        if (value <= 0) {
            throw new IllegalArgumentException("分页参数 " + word + "异常");
        }
        return value;
    }

    public String getWp(int pageNum, int pageSize) throws JsonProcessingException {
        ObjectMapper jsonMapper = new ObjectMapper();
        ObjectNode jsonObject = jsonMapper.createObjectNode();
        jsonObject.put("pageNum", pageNum);  // pageNum + 1
        jsonObject.put("pageSize", pageSize);    // pageSize 不变
        String jsonString = jsonMapper.writeValueAsString(jsonObject);
        String encode = URLEncoder.encode(jsonString, StandardCharsets.UTF_8);
        return encode;
    }
}
